package codeine.command_peer;


import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import codeine.servlet.AbstractServlet;
import codeine.servlet.HtmlHeaderWriter;

import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.google.inject.Inject;
import com.google.inject.Provider;

public class AllNodesCommandServlet extends AbstractServlet
{
	static final Logger log = Logger.getLogger(AllNodesCommandServlet.class);
	private static final long serialVersionUID = 1L;
	
	@Inject private HtmlHeaderWriter htmlHeaderWriter;
	@Inject private Provider<AllNodesCommandExecuter> allNodesCommandExecuterProvider;
	
	@Override
	protected void myPost(HttpServletRequest request, HttpServletResponse response)
	{
		log.info("AllNodesCommandServlet started");
		getWriter(response);
		String userArgs = request.getParameter("user_args");
		if (null == userArgs)
		{
			userArgs = "";
		}
		String project = request.getParameter("project");
		String command = request.getParameter("command");
		htmlHeaderWriter.writeHeader(request, response, project, project + " / " + command);
		String nodes = request.getParameter("nodes");
		List<String> nodeList = Lists.newArrayList(Splitter.on(",").omitEmptyStrings().split(nodes));
		getWriter(response).write("<div id='progressbarall'></div>\n");
		getWriter(response).write("<div id='progressbarfailed'></div>\n");
		getWriter(response).write("<script>$( '#progressbarall' ).progressbar({value: 0});</script>");
		getWriter(response).write("<script>$( '#progressbarfailed' ).progressbar({value: 0});</script>");
		getWriter(response).write("<script>$( '#progressbarall > div ' ).css({background: '#0B0B61'});</script>");
		getWriter(response).write("<script>$( '#progressbarfailed > div ' ).css({background: '#8A084B'});</script>");
		getWriter(response).write("<script>$( '#progressbarall' ).progressbar('option', 'max', " + nodeList.size() + ");</script>");
		getWriter(response).write("<script>$( '#progressbarfailed' ).progressbar('option', 'max', " + nodeList.size() + ");</script>");
		allNodesCommandExecuterProvider.get().executeOnAllNodes(response, userArgs, project, command, nodeList);
		htmlHeaderWriter.writeFooter(response);
		log.info("doRestart() - command finished");
	}
}
